import React from 'react'
import { Link } from 'react-router-dom'
import api from '@/api'
import { 
  Row,
  Button,
  Form,
  Select,
  Input,
  InputNumber,
  Icon,
  message
} from 'antd'
const FormItem = Form.Item
const Option = Select.Option

class Advimg_id extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      id: '',
      form: {
        // created_at: '',
        img_url: '',
        cover: '', // 展示用 带http
        sort: '',
        type: '',
        type_name: '',
        url: ''
      },
      page: {
        title: ''
      },
      maps: [],
      saving: false
    }
  }
  async componentWillMount(){
    this.mapsfun()
    const id = this.props.match.params.id
    const isNew = isNaN(id)
    const { page, form } = this.state 
    page.title = (isNew ? '新增' : '修改') + '分类'
    if (!isNew) {
      api.advimg_getdetails(id).then(({ data }) => {
        if (data.status === 'success') {
          const ad = data.data.ad
          form.created_at = ad.created_at
          const imgurlArr = ad.img_url.split('/')
          form.img_url = `${imgurlArr[imgurlArr.length - 2]}/${imgurlArr[imgurlArr.length - 1]}`
          form.cover = ad.img_url
          form.sort = ad.sort
          form.type = ad.type
          form.type_name = ad.type_name
          form.url = ad.url
          this.setState({
            form, isNew, id, page
          })
          this.props.form.setFieldsValue({
            type: form.type,
            url: form.url,
            sort: form.sort
          })
        }
      }).catch(() => {
        this.setState({
          isNew, id, page
        })
      })
    }
  }
  // 分类数据
  mapsfun () {
    api.advimg_typemaps().then(({ data }) => {
      this.setState({maps: data.data.maps})
    })
  }
  deteleimg  = (e) => {
    e.stopPropagation()
    const {form} = this.state
    form.img_url = ''
    form.cover = ''
    this.setState({form})
  }
  setAvatar = (e) => {
    e.preventDefault()
    e.stopPropagation()
    this.refs.avatarInput.click()
  }
  changeImage = (e) => {
    const file = e.target.files[0]
    const formData = new FormData()
    if (file.type !== 'image/png' && file.type !== 'image/jpeg') {
      message.warning('请选择图片！')
      return false
    }
    formData.append('file', file) // 数据
    formData.append('type', 'IMAGE')
    api.file_uploadimg(formData)
      .then(({ data }) => {
        if (data.status === 'success') {
          const form = this.state.form
          const { data: { resource }} = data
          form.img_url = resource.file_name
          form.cover = resource.url
          this.setState({form})
        } else {
          message.error('上传失败')
        }
      })
  }
  handleSubmit = (e) => {
    e.preventDefault()
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const handleWay = this.state.isNew ?  api.advimg_add : api.advimg_elt
        const form = this.state.form
        handleWay(this.state.id, {type: form.type, sort: form.sort, img_url: form.img_url, url: form.url})
          .then(({ data }) => {
            if(data.status === 'success'){
              setTimeout(() => {
                this.props.history.goBack() 
              }, 1000)
            }
          })
      }
    })
  }
  render(){
    const { page, form, maps} = this.state
    const { getFieldDecorator } = this.props.form
    return(
      <div>
        <Row className="mariya-filter-form">
          <div className="mariya-filter-form__title">{page.title }</div>
          <div className="mariya-filter-form__group">
            <Link to="/advimg">
              <Button type="default" icon="el-icon-back">返回</Button>
            </Link>
          </div>
        </Row>
        <Row className="mariya-form mariya-form--mini">
          <Row className="mariya-table__entity">
            <Form
              className="mariya-filter-form__entity"
              style={{paddingTop: '30px'}}
              label-width="100px"
              onSubmit={this.handleSubmit}
              labelCol={{span: 4 }}
              wrapperCol={{span: 14 }}
            >
            <FormItem label="类型">
            {
              getFieldDecorator('type', {
                rules: [{ required: true, message: '分类名称不能为空' }]
              })(
                <Select multiple="multiple" style={{width: '200px'}} placeholder="请选择广告分类">
                  {
                    maps.map((item) => {
                      return <Option key={item.value}>{item.label}</Option>
                    })
                  }
                </Select>
              )
            }
            </FormItem>
            <FormItem label="链接地址">
              {
                getFieldDecorator('url', {
                  rules: [{ required: true, message: '链接地址不能为空' }]
                })(
                  <Input placeholder="请输入分类名称"/>
                )
              }
            </FormItem>
            <FormItem label="排序">
              {
                getFieldDecorator('sort', {
                  rules: [{ required: true, message: '排序不能为空' }]
                })(
                  <InputNumber size="large" min={1} style={{width: '100%'}}/>
                )
              }
            </FormItem>
            <FormItem label="排序" >
            <section className="code-box-demo">
              <span className="">
                <div className="ant-upload ant-upload-select ant-upload-select-text">
                  <span className="ant-upload" role="button">
                    <input
                      type="file"
                      ref="avatarInput"
                      accept="image/png, image/jpeg, image/jpg"
                      style={{display: 'none'}}
                      onChange={this.changeImage}
                      />
                    <button type="button" className="ant-btn" onClick={this.setAvatar}>上传图片</button>
                  </span>
                </div>
                <div>只能上传jpg/png文件，且不超过500kb</div>
                <div className="ant-upload-list ant-upload-list-text">
                  <div className="ant-upload-list-item ant-upload-list-item-done">
                    <div className="ant-upload-list-item-info" style={{display: form.cover !== '' ? 'block': 'none'}}>
                      <p className="ant-upload-list-item-name">{form.cover}</p>
                      <Icon type="close" onClick={this.deteleimg}/>
                    </div>
                  </div>
                </div>
              </span>
              <img src={form.cover} alt="cover"/>
            </section>
            </FormItem>
            <FormItem wrapperCol={{ span: 14, offset: 4 }}>
              <Button type="primary" htmlType="submit">提交设置</Button>
            </FormItem>
          </Form>
          </Row>
        </Row>
      </div>
    )
  }  
}
export default Form.create({})(Advimg_id)

